const express = require("express");
const router = express.Router();
const adminUserHandler = require("../routes_handle/admin_user");
const { CODE, Response } = require("../utils/response");
const { checkPermission } = require("../middleware/permission");

// 获取用户列表
router.get("/admin/user/list", async (req, res, next) => {
  try {
    const { page = 1, pageSize = 10, FUsername, departmentId } = req.query;
    const users = await adminUserHandler.getUserList({
      page,
      pageSize,
      FUsername,
      departmentId,
    });
    res.status(CODE.SUCCESS).json(Response.success(users));
  } catch (err) {
    next(err);
  }
});
// 获取用户列表
router.post("/admin/user/listAll", async (req, res, next) => {
  try {
    const users = await adminUserHandler.getActiveUserList(
      req.body.FUsername
    );
    res.status(CODE.SUCCESS).json(Response.success(users));
  } catch (err) {
    next(err);
  }
});

// 获取单个用户详情
router.get("/admin/user/detail/:id", async (req, res, next) => {
  try {
    const user = await adminUserHandler.getUserById(req.params.id);
    res.status(CODE.SUCCESS).json(Response.success(user));
  } catch (err) {
    next(err);
  }
});

// 添加用户
router.post(
  "/admin/user/create",
  checkPermission("user:add"),
  async (req, res, next) => {
    try {
      const result = await adminUserHandler.createUser(req.body);
      res.status(CODE.SUCCESS).json(Response.success(result, "用户创建成功"));
    } catch (err) {
      next(err);
    }
  }
);

// 更新用户信息
router.post(
  "/admin/user/update",
  checkPermission("user:edit"),
  async (req, res, next) => {
    try {
      await adminUserHandler.updateUser(req.body);
      res.status(CODE.SUCCESS).json(Response.success(null, "用户更新成功"));
    } catch (err) {
      next(err);
    }
  }
);

// 删除用户
router.post(
  "/admin/user/delete",
  checkPermission("user:delete"),
  async (req, res, next) => {
    try {
      await adminUserHandler.deleteUser(req.body.FUserId);
      res.status(CODE.SUCCESS).json(Response.success(null, "用户删除成功"));
    } catch (err) {
      next(err);
    }
  }
);

// 更新用户状态
router.post(
  "/admin/user/status/:id",
  checkPermission("user:edit"),
  async (req, res, next) => {
    try {
      const { FIsActive } = req.body;
      await adminUserHandler.updateUserStatus(req.params.id, FIsActive);
      res.status(CODE.SUCCESS).json(Response.success(null, "用户状态更新成功"));
    } catch (err) {
      next(err);
    }
  }
);

module.exports = router;
